package com.sdy.resdir.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.resdir.biz.mapper.RdIpChangeMapper;
import com.sdy.resdir.biz.mapper.RdIpUpdateApplicationMapper;
import com.sdy.resdir.biz.mapper.RdSystemIpMapper;
import com.sdy.resdir.biz.model.*;
import com.sdy.resdir.biz.mapper.RdSelfBuiltSystemMapper;
import com.sdy.resdir.biz.param.OrderUserInfoParam;
import com.sdy.resdir.biz.service.*;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.el.parser.AstAssign;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.security.x509.RDN;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.*;

/**
 * <p>
 * 自建系统 服务实现类
 * </p>
 *
 * @author hyh
 * @since 2019-10-24
 */
@Slf4j
@Service
public class RdSelfBuiltSystemServiceImpl extends BaseServiceImpl<RdSelfBuiltSystem> implements RdSelfBuiltSystemService {
    @Resource
    private RdSelfBuiltSystemMapper rdSelfBuiltSystemMapper;
    @Resource
    private RdSystemIpMapper ipMapper;
    @Resource
    private RdIpChangeMapper rdIpChangeMapper;
    @Autowired
    private RdIpUpdateApplicationService ipApplyService;
    @Autowired
    private RdIpUpdateApplicationMapper ipApplyMapper;
    @Autowired
    private RdResourceApplicationDetailService resOrderService;
    @Autowired
    private RdOrderAppService orderAppService;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private RdResourceDirService rdResourceDirService;
    @Autowired
    private RdSystemIpService rdSystemIpService;
    @Autowired
    private RdIpChangeService rdIpChangeService;
    @Autowired
    private RdIpImpleOrderService ipImpleOrderService;
    @Value("${res.dept.code}")
    private String deptCode;

    @Override
    public int createApp(RdSelfBuiltSystem app, Integer userId) throws BizException {
        // 获取用户信息以及角色信息
        UserDTO user = userQueryApi.getUser(userId);
        app.setDeptId(user.getOwnDeptId());
        List<RdSystemIp> ipList = app.getIpList();
        checkIp(ipList, user.getOwnDeptId());
        app.setSysCode(UUID.randomUUID().toString());
        app.setCreateTime(new Date());
        app.setUserId(userId);
        int appState = rdSelfBuiltSystemMapper.insert(app);
        for (RdSystemIp systemIp : ipList) {
            systemIp.setCreateTime(new Date()).setRelfSysId(app.getId());
        }
        int appIpState = 1;
        if (!ipList.isEmpty()) {
            appIpState = ipMapper.batchInsert(ipList);
        }
        return appState == 0 || appIpState == 0 ? 0 : 1;
    }

    private boolean checkIp(List<RdSystemIp> ipList, Integer deptId) throws BizException {
        // 首先检查此次传入的ip列表是否存在重复的ip
        List<String> distIpList = ipList.stream().map(RdSystemIp::getIp).distinct().collect(Collectors.toList());
        Assert.isTrue(ipList.size() != distIpList.size(), "ip列表不可重复");

        // 保证该部门添加的ip不存在与其他部门,即不与其他部门相同
        List<RdSelfBuiltSystem> apps = rdSelfBuiltSystemMapper.selectList(Wrappers.<RdSelfBuiltSystem>lambdaQuery().notIn(RdSelfBuiltSystem::getDeptId, deptId));
        if (!apps.isEmpty()) {
            List<RdSystemIp> rdSystemIps = ipMapper.selectList(Wrappers.<RdSystemIp>lambdaQuery().in(RdSystemIp::getRelfSysId, apps.stream().map(RdSelfBuiltSystem::getId).collect(toList())));
            boolean disjoint = Collections.disjoint(rdSystemIps.stream().map(RdSystemIp::getIp).collect(toList()), ipList.stream().map(RdSystemIp::getIp).collect(toList()));
            Assert.isTrue(!disjoint, "当前ip列表中与其他部门使用的ip存在相同值,请修改");
        }
        return true;
    }

    @Override
    public void updateApp(RdSelfBuiltSystem app, Integer userId) throws BizException {
        app.setUpdateTime(new Date()).setCreateTime(null).setSysCode(null).setDeptId(null);
        int i = rdSelfBuiltSystemMapper.updateById(app);
        UserDTO user = userQueryApi.getUser(userId);
        // 判断当前修改的ip中是否涉及到资源申请单中绑定的ip如果涉及到则不能进行修改操作
        List<RdResourceApplicationDetail> orderList = resOrderService.list(Wrappers.<RdResourceApplicationDetail>lambdaQuery()
                .eq(RdResourceApplicationDetail::getDeptId, user.getOwnDeptId())
                .in(RdResourceApplicationDetail::getState, Arrays.asList(2, 3, 4)));
        if (!orderList.isEmpty()) {
            List<String> applyNos = orderList.stream().map(RdResourceApplicationDetail::getApplyNumChild).collect(toList());
            List<RdOrderApp> orderApps = orderAppService.list(Wrappers.<RdOrderApp>lambdaQuery().in(RdOrderApp::getApplyNum, applyNos));
            // 筛选出原有的ip,对比申请单绑定的ip列表判断要修改的ip是否绑定了申请单,如果有则不可进行修改
            List<RdSystemIp> ips = app.getIpList().stream().filter(appip -> appip.getId() != null).collect(toList());
            // TODO 需要在OrderApp表中存入IP的ID以进行判断该IP是否能够变动
            for (RdOrderApp orderApp : orderApps) {
                for (RdSystemIp ip : ips) {
                    Assert.isTrue(orderApp.getIp().equals(ip.getIp()), "当前Ip绑定了资源申请单,不可进行修改操作");
                }
            }
        }
        // 根据ip的变动生成对应的IP修改申请单
        setAppIpCreateOrder(app, userId);
    }

    private void delAppIp(RdSelfBuiltSystem app, UserDTO user) throws BizException {
        // 首先对已经删除的IP生成实施工单
        List<String> delIdList = app.getDelIdList();
        if (!delIdList.isEmpty()) {
            List<RdSystemIp> rdSystemIps = ipMapper.selectList(Wrappers.<RdSystemIp>lambdaQuery().in(RdSystemIp::getId, delIdList));
            List<RdIpChange> ipChanges = new ArrayList<>();
            // 将绑定了资源的IP生成IP Change 记录
            List<RdSystemIp> collect = rdSystemIps.stream().filter(ip -> StringUtil.isNotEmpty(ip.getResIdList()) && StringUtil.isNotBlank(ip.getResIdList())).collect(toList());
            for (RdSystemIp systemIp : collect) {
                RdIpChange rdIpChange = new RdIpChange()
                        .setOldIp(systemIp.getIp())
                        .setOldResIdList(systemIp.getResIdList())
                        .setAppId(app.getId())
                        .setCreateTime(new Date())
                        .setType(2);
                ipChanges.add(rdIpChange);
            }
            int i = 0;
            if (!ipChanges.isEmpty()) {
                i = rdIpChangeMapper.batchInsert(ipChanges);
            }
            // 创建实施工单对象
            RdIpImpleOrder rdIpImpleOrder = new RdIpImpleOrder()
                    .setAppId(app.getId())
                    .setOrderNo(System.currentTimeMillis() + "")
                    .setIpId(ipChanges.stream().map(ip -> ip.getId() + "").collect(joining(",")))
                    .setUserId(user.getId())
                    .setDeptId(userQueryApi.getDeptByCode(deptCode).getId())
                    .setCreateTime(new Date())
                    .setUserName(user.getName())
                    .setState(0)
                    .setType(2);
            boolean save = ipImpleOrderService.save(rdIpImpleOrder);
            Assert.isTrue(!save, "操作出现错误,请重试");
            int delete = ipMapper.delete(Wrappers.<RdSystemIp>lambdaUpdate().in(RdSystemIp::getId, rdSystemIps.stream().map(RdSystemIp::getId).collect(toList())));
            Assert.isTrue(delete == 0, "操作出现错误，请重试");
        }
    }

    @Override
    public RdSelfBuiltSystem getAppInfo(Integer id) throws BizException {
        RdSelfBuiltSystem app = rdSelfBuiltSystemMapper.selectOne(Wrappers.<RdSelfBuiltSystem>lambdaQuery().eq(RdSelfBuiltSystem::getId, id));
        Assert.isNull(app, "没有查询到该自建系统");
        List<RdSystemIp> list = ipMapper.selectList(Wrappers.<RdSystemIp>lambdaQuery().eq(RdSystemIp::getRelfSysId, app.getId()));
        app.getIpList().addAll(setAppIpState(list, app.getDeptId()));
        return app;
    }

    private List<RdSystemIp> setAppIpState(List<RdSystemIp> ipList, Integer deptId) {
        // 首先查询该用户所有在进行中的订单
        List<RdIpUpdateApplication> list = ipApplyService.list(Wrappers.<RdIpUpdateApplication>lambdaQuery().eq(RdIpUpdateApplication::getDeptId, deptId).in(RdIpUpdateApplication::getCurrentState, Arrays.asList(2, 3, 4)));
        List<String> ipIdList = list.stream().map(RdIpUpdateApplication::getIpId).collect(Collectors.toList());
        StringBuffer ipId = new StringBuffer();
        ipIdList.forEach(ip -> ipId.append(ip + ","));
        if (!list.isEmpty()) {
            // 根据这些订单存储的ipChange表的ID查询ipChange表
            List<RdIpChange> ipChangeList = rdIpChangeMapper.selectList(Wrappers.<RdIpChange>lambdaQuery().in(RdIpChange::getId, Arrays.asList(new String(ipId).split(","))).isNotNull(RdIpChange::getAimsId));
            for (RdSystemIp appIp : ipList) {
                for (RdIpChange ipChange : ipChangeList) {
                    // 没有任何限制的IP
                    if (appIp.getId().equals(ipChange.getAimsId())) {
                        // 需要进行限制的IP
                        if (!appIp.getIp().equals(ipChange.getNewIp())) {
                            appIp.setState(2);
                        }
                        if (null == appIp.getResIdList() || !appIp.getResIdList().equals(ipChange.getNewResIdList())) {
                            appIp.setState(1);
                        }
                    } else {
                        if (appIp.getState() == null) {
                            appIp.setState(0);
                        }
                    }
                }
            }
        } else {
            ipList.forEach(appIp -> {
                appIp.setState(0);
            });
        }
        return ipList;
    }

    private void setAppIpCreateOrder(RdSelfBuiltSystem app, Integer userId) throws BizException {
        UserDTO user = userQueryApi.getUser(userId);
        // 获取删除掉的IP 的 ID 然后根据ID生成对应的实施工单后执行删除操作
        delAppIp(app, user);
        List<RdSystemIp> ipList = app.getIpList();
        checkIp(ipList, user.getOwnDeptId());
        // 筛选出需要新增的数据
        List<RdSystemIp> addIpList = ipList.stream().filter(appIp -> appIp.getId() == null).collect(Collectors.toList());
        // 直接新增没有绑定应用的IP
        List<RdSystemIp> newIpList = addIpList.stream().filter(add -> StringUtil.isBlank(add.getResIdList()) && StringUtil.isEmpty(add.getResIdList())).collect(Collectors.toList());
        // 给需要新增的应用添加APPid
        newIpList.forEach(ip -> {
            ip.setRelfSysId(app.getId());
        });
        if (!newIpList.isEmpty()) {
            for (RdSystemIp systemIp : newIpList) {
                systemIp.setCreateTime(new Date()).setRelfSysId(app.getId());
            }
            ipMapper.batchInsert(newIpList);
        }
        // 新增的ip中如果绑定了应用则生成订单
        List<RdSystemIp> newOrderIpList = addIpList.stream().filter(add -> !StringUtil.isBlank(add.getResIdList()) && !StringUtil.isEmpty(add.getResIdList())).collect(Collectors.toList());
        List<RdIpChange> allOrderIp = new ArrayList<>();
        List<RdIpChange> addOrderIp = new ArrayList<>();
        if (!newOrderIpList.isEmpty()) {
            addNewIpOrder(app, newOrderIpList, addOrderIp);
        }
        // 筛选出原有的数据
        List<RdSystemIp> updateIpList = ipList.stream().filter(appip -> appip.getId() != null).collect(Collectors.toList());
        List<RdSystemIp> bindResIpList = updateIpList.stream().filter(ip -> null != ip.getResIdList() && StringUtil.isNotBlank(ip.getResIdList()) && StringUtil.isNotEmpty(ip.getResIdList())).collect(toList());
        List<Integer> ipIdList = bindResIpList.stream().map(ip -> ip.getId()).collect(toList());
        if (!ipIdList.isEmpty()) {
            // 根据ID查询数据库中的数据
            List<RdSystemIp> gsAppIps = ipMapper.selectList(
                    Wrappers.<RdSystemIp>lambdaQuery().in(RdSystemIp::getId, ipIdList));
            // 对比是否变更了IP地址或者变更了绑定的资源,将需要生成订单的数据取出
//            List<RdIpChange> updateIpOrder = new ArrayList<>();
            for (RdSystemIp updateAppIp : updateIpList) {
                for (RdSystemIp appIp : gsAppIps) {
                    if (updateAppIp.getId().equals(appIp.getId())) {
                        boolean ipState = updateAppIp.getIp().equals(appIp.getIp());
                        boolean resIdListState = updateAppIp.getResIdList().equals(appIp.getResIdList());
                        if (ipState && resIdListState) {
                            continue;
                        }
                        List<String> newResIdList = new ArrayList<>();
                        List<String> oldResIdList = new ArrayList<>();
                        if (StringUtil.isNotBlank(updateAppIp.getResIdList())) {
                            newResIdList = Arrays.asList(updateAppIp.getResIdList().split(","));
                        }
                        if (StringUtil.isNotBlank(appIp.getResIdList())) {
                            oldResIdList = Arrays.asList(appIp.getResIdList().split(","));
                        }
                        List<List<RdResourceDir>> groupBySourceDeptId = new ArrayList<>();
                        List<List<RdResourceDir>> groupByResPower = new ArrayList<>();
                        // ip修改
                        if (!ipState) {
                            deleteOldAndAddNewOrder(app, addOrderIp, appIp, updateAppIp, oldResIdList, newResIdList, groupBySourceDeptId, groupByResPower, 1, appIp.getId());
                        }
                        //如果ip没改,资源修改
                        if (ipState) {
                            // 删除的资源
                            List<String> delResList = new ArrayList<>();
                            // 新增的资源
                            List<String> addResList = new ArrayList<>();
                            // 获取新增和删除的资源
                            getDelAndNewResIdList(newResIdList, oldResIdList, delResList, addResList);
                            // 新增资源，生成ipChange
                            if (!addResList.isEmpty()) {
                                deleteOldAndAddNewOrder(app, addOrderIp, appIp, updateAppIp, delResList, addResList, groupBySourceDeptId, groupByResPower, 1, appIp.getId());
                            } else {
                                delResCreateImpleOrder(app, user, updateAppIp, appIp, delResList);

                            }
                        }
                    }
                }
            }
//            if (!updateIpOrder.isEmpty()) {
//                allOrderIp.addAll(updateIpOrder);
//            }
        } else {
            // 如果都是没有绑定应用的操作，则直接修改即可
            if (!updateIpList.isEmpty()) {
                List<String> oldIpList = updateIpList.stream().map(RdSystemIp::getIp).collect(toList());
                if (!oldIpList.isEmpty()) {
                    List<RdSystemIp> systemIps = rdSystemIpService.list(new LambdaQueryWrapper<RdSystemIp>()
                            .eq(RdSystemIp::getRelfSysId, app.getId())
                            .in(RdSystemIp::getIp, oldIpList));
                    List<RdIpImpleOrder> orderList = new ArrayList<>();
                    for (RdSystemIp oldIp : systemIps) {
                        if (oldIp.getResIdList() != null && StringUtil.isNotBlank(oldIp.getResIdList())) {
                            RdIpChange rdIpChange = new RdIpChange()
                                    .setType(1)
                                    .setAppId(app.getId())
                                    .setOldIp(oldIp.getIp())
                                    .setNewIp(oldIp.getIp())
                                    .setAimsId(null)
                                    .setOldResIdList(StringUtil.join(oldIp.getResIdList(), ","))
                                    .setNewResIdList(null)
                                    .setCreateTime(new Date());
                            boolean save = rdIpChangeService.save(rdIpChange);
                            Assert.notTrue(save, "生成实施工单失败");
                            orderList.add(new RdIpImpleOrder()
                                    .setAppId(app.getId())
                                    .setOrderNo(System.currentTimeMillis() + "")
                                    .setIpId(rdIpChange.getId().toString())
                                    .setUserId(user.getId())
                                    .setDeptId(userQueryApi.getDeptByCode(deptCode).getId())
                                    .setCreateTime(new Date())
                                    .setUserName(user.getName())
                                    .setState(0)
                                    .setType(1));
                        }
                    }
                    if (!orderList.isEmpty()) {
                        Integer i = ipImpleOrderService.insertBatch(orderList);
                        Assert.isNull(i, "生成实施工单失败");
                    }
                }
            }
        }
        updateIpList.removeAll(bindResIpList);
        List<RdSystemIp> noBindResIpList = updateIpList;
        if (!noBindResIpList.isEmpty()) {
            checkOldIpIsBindRes(noBindResIpList, app.getId(), userId, user.getName());
        }
        // 查询出改用户的部门信息以及角色信息,提取出需要的角色信息
        OrderUserInfoParam orderUserInfoParam = new OrderUserInfoParam().setUserId(userId).setDeptId(user.getOwnDeptId());
        int type = allOrderIp.size() > addOrderIp.size() ? 1 : 0;
        allOrderIp.addAll(addOrderIp);
        if (!allOrderIp.isEmpty()) {
            String content = "用户:" + user.getName() + "修改自建系统生成了IP申请单";
            createIpOrder(allOrderIp, app.getId(), orderUserInfoParam, content, type);
        }
    }

    private void delResCreateImpleOrder(RdSelfBuiltSystem app, UserDTO user, RdSystemIp updateAppIp, RdSystemIp appIp, List<String> delResList) throws BizException {
        if (!delResList.isEmpty()) {
            RdIpChange rdIpChange = new RdIpChange()
                    .setType(1)
                    .setAppId(app.getId())
                    .setOldIp(appIp.getIp())
                    .setNewIp(updateAppIp.getIp())
                    .setAimsId(appIp.getId())
                    .setOldResIdList(StringUtil.join(delResList, ","))
                    .setNewResIdList(null)
                    .setCreateTime(new Date());
            boolean save = rdIpChangeService.save(rdIpChange);
            Assert.notTrue(save, "生成申请单失败");
            createDelImpleOrder(app, user, 1, rdIpChange);
        }
    }

    private void getDelAndNewResIdList(List<String> newResIdList, List<String> oldResIdList, List<String> delResList, List<String> addResList) {
        if (!newResIdList.isEmpty() && oldResIdList.isEmpty()) {
            addResList.addAll(newResIdList);
        } else if (newResIdList.isEmpty() && !oldResIdList.isEmpty()) {
            delResList.addAll(oldResIdList);
        } else if (!newResIdList.isEmpty() && !oldResIdList.isEmpty()) {
            for (String newResId : newResIdList) {
                for (String oldResId : oldResIdList) {
                    if (!oldResIdList.contains(newResId) && !addResList.contains(newResId)) {
                        addResList.add(newResId);
                    }
                    if (!newResIdList.contains(oldResId) && !delResList.contains(oldResId)) {
                        delResList.add(oldResId);
                    }
                }
            }
        }
    }

    private void addNewIpOrder(RdSelfBuiltSystem app, List<RdSystemIp> newOrderIpList, List<RdIpChange> addOrderIp) {
        for (RdSystemIp newOrder : newOrderIpList) {
            if (StringUtil.isNotBlank(newOrder.getResIdList())) {
                String[] resIdList = newOrder.getResIdList().split(",");
                List<String> list = new ArrayList<>(Arrays.asList(resIdList));
                List<List<RdResourceDir>> groupBySourceDeptId = new ArrayList<>();
                List<List<RdResourceDir>> groupByResPower = new ArrayList<>();
                // 通过资源权限分组
                deleteOldAndAddNewOrder(app, addOrderIp, null, newOrder, null, list, groupBySourceDeptId, groupByResPower, 0, null);
            }
        }
    }

    private void createDelImpleOrder(RdSelfBuiltSystem app, UserDTO user, Integer type, RdIpChange rdIpChange) {
        RdIpImpleOrder rdIpImpleOrder = new RdIpImpleOrder()
                .setAppId(app.getId())
                .setOrderNo(System.currentTimeMillis() + "")
                .setIpId(rdIpChange.getId().toString())
                .setUserId(user.getId())
                .setDeptId(userQueryApi.getDeptByCode(deptCode).getId())
                .setCreateTime(new Date())
                .setUserName(user.getName())
                .setState(0)
                .setType(type);
        boolean save = ipImpleOrderService.save(rdIpImpleOrder);
        try {
            Assert.notTrue(save, "生成删除ip的实施工单失败");
        } catch (BizException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param app
     * @param addOrderIp
     * @param oldOrder
     * @param newOrder
     * @param oldResIdList
     * @param newResIdList
     * @param groupBySourceDeptId
     * @param groupByResPower
     * @param type
     * @param aimsId
     */
    private void deleteOldAndAddNewOrder(RdSelfBuiltSystem app, List<RdIpChange> addOrderIp, RdSystemIp oldOrder, RdSystemIp newOrder, List<String> oldResIdList, List<String> newResIdList, List<List<RdResourceDir>> groupBySourceDeptId, List<List<RdResourceDir>> groupByResPower, Integer type, Integer aimsId) {
        // 新资源
        List<RdResourceDir> newResList = new ArrayList<>();
        if (newResIdList != null && !newResIdList.isEmpty()) {
            newResList = rdResourceDirService.list(new LambdaQueryWrapper<RdResourceDir>()
                    .in(RdResourceDir::getId, newResIdList));
        }
        // 旧资源
        List<RdResourceDir> oldResList = new ArrayList<>();
        if (oldResIdList != null && !oldResIdList.isEmpty()) {
            oldResList = rdResourceDirService.list(new LambdaQueryWrapper<RdResourceDir>()
                    .in(RdResourceDir::getId, oldResIdList));
        }
        if (!newResList.isEmpty()) {
            newResList.stream().collect(Collectors.groupingBy(RdResourceDir::getResPower, Collectors.toList()))
                    .forEach((res, dirList) -> {
                        groupByResPower.add(dirList);
                    });
        }
        for (List<RdResourceDir> oneResList : groupByResPower) {
            // 公开资源直接生成订单
            if (!oneResList.isEmpty() && oneResList.get(0).getResPower() == 1) {
                addIpOrder(app, addOrderIp, oldOrder, newOrder, oldResList, oneResList, type, aimsId);
                // 受限资源按提供部门分组
            } else if (oneResList.get(0).getResPower() == 2) {
                oneResList.stream().collect(Collectors.groupingBy(RdResourceDir::getResSourceDeptId, Collectors.toList()))
                        .forEach((res, dirList) -> {
                            groupBySourceDeptId.add(dirList);
                        });
                // 通过不同部门生成不同订单
                for (List<RdResourceDir> resByDeptId : groupBySourceDeptId) {
                    addIpOrder(app, addOrderIp, oldOrder, newOrder, oldResList, resByDeptId, type, aimsId);
                }
            }
        }
    }

    /**
     * 新增ip修改单
     *
     * @param app
     * @param addOrderIp
     * @param newOrder
     * @param oldResList
     * @param newResList
     */
    private void addIpOrder(RdSelfBuiltSystem app, List<RdIpChange> addOrderIp, RdSystemIp oldOrder, RdSystemIp newOrder, List<RdResourceDir> oldResList, List<RdResourceDir> newResList, Integer type, Integer aimsId) {
        List<Integer> oldResIdList = new ArrayList<>();
        List<Integer> newResIdList = new ArrayList<>();
        String oldResIdListString = null;
        String newResIdListString = null;
        if (oldResList != null && !oldResList.isEmpty()) {
            oldResIdList = oldResList.stream().map(RdResourceDir::getId).collect(toList());
            oldResIdListString = StringUtils.join(oldResIdList, ",");
        }
        if (newResList != null && !newResList.isEmpty()) {
            newResIdList = newResList.stream().map(RdResourceDir::getId).collect(toList());
            newResIdListString = StringUtils.join(newResIdList, ",");
        }
        addOrderIp.add(new RdIpChange()
                .setType(type)
                .setAppId(app.getId())
                .setOldIp(oldOrder != null ? oldOrder.getIp() : null)
                .setNewIp(newOrder != null ? newOrder.getIp() : null)
                .setAimsId(aimsId)
                .setOldResIdList(oldResIdListString)
                .setNewResIdList(newResIdListString)
                .setCreateTime(new Date()));
    }


    /**
     * 检查原本存在的IP,如果原本绑定了资源现在取消了则生成IP实施单
     *
     * @param newIpList 被修改了的原本的库中的数据(可能进行了IP的修改&进行了资源的取消绑定)
     * @return
     */
    private void checkOldIpIsBindRes(List<RdSystemIp> newIpList, Integer appId, Integer userId, String userName) throws BizException {
        List<String> idList = newIpList.stream().map(ip -> ip.getId() + "").collect(toList());
        List<RdSystemIp> ips = ipMapper.selectList(Wrappers.<RdSystemIp>lambdaQuery().in(RdSystemIp::getId, idList));
        // 生成取消绑定资源的IP的修改记录
        List<RdIpChange> ipChanges = new ArrayList<>();
        for (RdSystemIp oldIp : ips) {
            for (RdSystemIp newIp : newIpList) {
                // // 同个IP  IP地址无变动 同时 也取消了资源列表绑定
                if (oldIp.getId() != null && newIp.getId() != null && StringUtil.isNotBlank(oldIp.getResIdList()) && StringUtil.isNotBlank(newIp.getResIdList()) && oldIp.getId().equals(newIp.getId()) && oldIp.getIp().equals(newIp.getIp()) && !oldIp.getResIdList().equals(newIp.getResIdList())) {
                    RdIpChange rdIpChange = new RdIpChange()
                            .setAppId(appId)
                            .setAimsId(newIp.getId())
                            .setOldIp(oldIp.getIp())
                            .setNewIp(newIp.getIp())
                            .setOldResIdList(oldIp.getResIdList())
                            .setNewResIdList(newIp.getResIdList())
                            .setType(1);
                    ipChanges.add(rdIpChange);
                } else if (oldIp.getId() != null && newIp.getId() != null && StringUtil.isNotBlank(oldIp.getResIdList()) && StringUtil.isNotBlank(newIp.getResIdList()) && oldIp.getId().equals(newIp.getId()) && !oldIp.getIp().equals(newIp.getIp()) && !oldIp.getResIdList().equals(newIp.getResIdList())) {
                    // 同个IP  IP地址有变动 同时 也取消了资源列表绑定
                    RdIpChange rdIpChange = new RdIpChange()
                            .setAppId(appId)
                            .setAimsId(newIp.getId())
                            .setOldIp(oldIp.getIp())
                            .setNewIp(newIp.getIp())
                            .setOldResIdList(oldIp.getResIdList())
                            .setNewResIdList(newIp.getResIdList())
                            .setType(1);
                    ipChanges.add(rdIpChange);
                }
            }
        }
        if (!ipChanges.isEmpty()) {
            // 将IP修改记录插入
            int ipChangeBatch = rdIpChangeMapper.batchInsert(ipChanges);
            Assert.isTrue(ipChangeBatch == 0, "IP修改记录生成错误");
            // 同时对取消绑定的资源的IP生成IP实施工单
            // 创建实施工单对象
            RdIpImpleOrder rdIpImpleOrder = new RdIpImpleOrder()
                    .setAppId(appId)
                    .setOrderNo(System.currentTimeMillis() + "")
                    .setIpId(ipChanges.stream().map(ip -> ip.getId() + "").collect(joining(",")))
                    .setUserId(userId)
                    .setDeptId(userQueryApi.getDeptByCode(deptCode).getId())
                    .setCreateTime(new Date())
                    .setUserName(userName)
                    .setState(0)
                    .setType(1);
            // 插入实施工单数据
            boolean ipImpleOrderState = ipImpleOrderService.save(rdIpImpleOrder);
            Assert.isTrue(!ipImpleOrderState, "IP实施工单生成失败");
        }
        // 之后对这些IP进行修改(无论是进行了IP的修改还是进行了资源的取消绑定操作都要进行修改)
        int ipUpdateState = ipMapper.batchUpdate(newIpList);
        Assert.isTrue(ipUpdateState == 0, "IP列表修改失败");
    }

    private static int checkNewResIdAndOldResId(String newResIds, String oldResIds) {
        // 如果旧数据为空，则代表原来没有绑定应用，现在需要添加应用
        if (null == oldResIds) {
            return 1;
        }
        String[] newResIdList = newResIds.split(",");
        String[] oldResIdList = oldResIds.split(",");
        // 长度相同但是内容不同，视为更换了绑定应用
        if (newResIdList.length == oldResIdList.length && !newResIds.equals(oldResIds)) {
            return 1;
        }
        // 如果是增加
        if (newResIdList.length > oldResIdList.length) {
            return 1;
        }
        // 如果是减少
        if (newResIdList.length < oldResIdList.length) {
            return 1;
        }
        return 0;
    }


    private void createIpOrder(List<RdIpChange> ipList, Integer appId, OrderUserInfoParam infoParam, String content, int type) throws BizException {
        Assert.isTrue(ipList.isEmpty(), "IP修改信息为空");
        int batchInsert = rdIpChangeMapper.batchInsert(ipList);
        List<String> newIpList = ipList.stream().map(ip -> ip.getId() + "").collect(toList());
//        List<String> newIpList = ipList.stream().map(RdIpChange::getNewIp).collect(toList());
        // ipChange资源列表
//        String resBuffer = ipList.stream().map(res -> res.getNewResIdList() + "").collect(joining(","));
        List<RdIpUpdateApplication> newApplyList = new ArrayList<>();
        for (String ip : newIpList) {
            long dateEx = System.currentTimeMillis();
            DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String timeEx = dateFormat.format(dateEx);
            int aEx = (int) (Math.random() * 900 + 100);
            String randomThree = Integer.toString(aEx);
            String randomNum = timeEx + randomThree;
            String applyNo = System.currentTimeMillis() + "-" + randomNum + "";
            RdIpUpdateApplication newApply = new RdIpUpdateApplication()
                    .setAppId(appId)
                    .setIpId(ip)
                    .setApplyNum(applyNo)
                    .setApplyUserId(infoParam.getUserId())
                    .setContent(content)
                    .setCurrentState(2)
                    .setCreateTime(new Date())
                    .setIsDone(0)
                    .setDeptId(infoParam.getDeptId())
                    .setType(type);
            newApplyList.add(newApply);
        }
        boolean save = ipApplyMapper.batchInsert(newApplyList);
        Assert.isTrue(batchInsert == 0 || !save, "生成IP需求申请单时出现错误");
    }


}
